<template>
    <view class="page">
        <u-sticky bgColor="#fff">
            <u-tabs :list="list" :current="current" @change="ChangeHandler"></u-tabs>
        </u-sticky>
        <view class="content">
            <!-- 个人-->
            <u-form v-if="type==1"
                    labelPosition="left"
                    labelAlign="right"
                    labelWidth="80"
                    :model="form1"
                    ref="uForm1">
                <u-form-item label="姓名" prop="name">
                    <u-input v-model="form1.name" placeholder="请输入姓名"></u-input>
                </u-form-item>
                <u-form-item label="身份证" prop="num">
                    <u-input v-model="form1.num" placeholder="请输入身份证"></u-input>
                </u-form-item>
                <u-form-item label="手机号" prop="phone">
                    <u-input v-model="form1.phone" placeholder="请输入手机号"></u-input>
                </u-form-item>
                <u-form-item label="签名" prop="ren_sign">
                    <u-button type="primary" text="点击签名" @click="openSign"></u-button>
                    <cat-signature canvasId="canvas1" @close="closeSign" @save="saveSign" :visible="showSign"></cat-signature>
                </u-form-item>
                <u-form-item>
                    <view style="margin-left: 40rpx">
                        <u-radio-group v-model="checked1">
                            <u-radio shape="square" :name="true" label="阅读并同意，《电子签名使用协议免责协议》"></u-radio>
                        </u-radio-group>
                    </view>
                </u-form-item>
            </u-form>

            <!--公司-->
            <u-form v-if="type==2"
                    labelPosition="left"
                    labelAlign="right"
                    labelWidth="100"
                    :model="form2"
                    ref="uForm2">
                <u-form-item label="企业名称" prop="unit">
                    <u-input v-model="form2.unit" placeholder="请输入企业名称"></u-input>
                </u-form-item>
                <u-form-item label="营业执照号" prop="unit_num">
                    <u-input v-model="form2.unit_num" placeholder="请输入营业执照号"></u-input>
                </u-form-item>
                <u-form-item label="法人身份证" prop="unit_number">
                    <u-input v-model="form2.unit_number" placeholder="请输入法人身份证"></u-input>
                </u-form-item>
                <u-form-item label="法人姓名" prop="unit_name">
                    <u-input v-model="form2.unit_name" placeholder="请输入法人姓名"></u-input>
                </u-form-item>
                <u-form-item label="法人手机号" prop="unit_phone">
                    <u-input v-model="form2.unit_phone" placeholder="请输入法人手机号"></u-input>
                </u-form-item>
                <u-form-item label="公司签章" prop="unit_sign">
                    <u-upload
                            :fileList="unitImgList"
                            @afterRead="afterRead"
                            @delete="deletePic"
                            name="unit"
                            multiple
                            :maxCount="1"
                    >
                    </u-upload>
                </u-form-item>
                <u-form-item>
                    <view style="margin-left: 40rpx">
                        <u-radio-group v-model="checked2">
                            <u-radio shape="square" :name="true" label="阅读并同意，《电子签名使用协议免责协议》"></u-radio>
                        </u-radio-group>
                    </view>
                </u-form-item>
            </u-form>
        </view>
        <view style="width:100%;height: 70px;background-color: #fff;position: fixed;bottom: 1px">
            <u-row>
                <u-button type="primary" text="保存" @click="save"></u-button>
            </u-row>

            <view class="safe-area-inset-bottom"></view>
        </view>
    </view>
</template>

<script>
    import catSignature from "../../../components/cat-signature.vue"
    export default {
        name: "signature",
        onReady() {
            // 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
            //如果rules中有自定义方法等，需要用此方法设置rules规则，否则微信小程序无效
            this.$refs.uForm1.setRules(this.rules1);
        },
        components:{
            catSignature
        },
        data(){
            return{
                showSign: false,
                current: 0,
                type: 1,
                unitImgList:[],
                list: [{
                    name: '个人',
                    type: 1
                }, {
                    name: '公司',
                    type: 2
                }],
                checked1: '',
                checked2: '',
                form1: {
                    name: '',
                    num: '',
                    phone: '',
                    ren_sign: '',
                },
                rules1: {
                    name: [{required: true, message: '请输入姓名', trigger: ['blur', 'change']}],
                    phone: [
                        {type: 'number', required: true, message: '请输入手机号', trigger: ['blur', 'change']},
                        {
                            // 自定义验证函数，见上说明
                            validator: (rule, value, callback) => {
                                // 上面有说，返回true表示校验通过，返回false表示不通过
                                // uni.$u.test.mobile()就是返回true或者false的
                                return uni.$u.test.mobile(value);
                            },
                            message: '手机号码不正确',
                            // 触发器可以同时用blur和change
                            trigger: ['change','blur'],
                        }
                    ],
                    num: [{required: true, message: '请输入身份证', trigger: ['blur', 'change']}],
                    // ren_sign: [{required: true, message: '请点击签名', trigger: ['blur', 'change']}],
                },

                form2: {
                    unit: '',
                    unit_num: '',
                    unit_number: '',
                    unit_name: '',
                    unit_phone: '',
                    unit_sign: '',
                },
                rules2: {
                    unit: [{required: true, message: '请输入企业名称', trigger: ['blur', 'change']}],
                    unit_num: [{required: true, message: '请输入营业执照号', trigger: ['blur', 'change']}],
                    unit_number: [{required: true, message: '请输入法人身份证', trigger: ['blur', 'change']}],
                    unit_name: [{required: true, message: '请输入法人姓名', trigger: ['blur', 'change']}],
                    unit_phone: [
                        {required: true, message: '请输入法人手机号', trigger: ['blur', 'change']},
                        {
                            // 自定义验证函数，见上说明
                            validator: (rule, value, callback) => {
                                // 上面有说，返回true表示校验通过，返回false表示不通过
                                // uni.$u.test.mobile()就是返回true或者false的
                                return uni.$u.test.mobile(value);
                            },
                            message: '手机号码不正确',
                            // 触发器可以同时用blur和change
                            trigger: ['change','blur'],
                        }
                    ],
                    // unit_sign: [{required: true, message: '请上传公司签章', trigger: ['blur', 'change']}],
                }
            }
        },
        methods:{
            openSign(){
                this.showSign = true;
            },
            closeSign(){
                this.showSign = false;
            },
            async saveSign(val){
                this.showSign = false;
                uni.showLoading({title: '正在上传'});
                this.form1.ren_sign = await this.uploadFilePromise(val);
                uni.hideLoading();
            },
            ChangeHandler(e){
                this.current = e.index;
                this.type = e.type;

                if (parseInt(e.type) === 1) {
                    this.$nextTick(() => {
                        this.$refs.uForm1.setRules(this.rules1);
                    });
                }else{
                    this.$nextTick(() => {
                        this.$refs.uForm2.setRules(this.rules2);
                    });
                }
            },

            // 删除图片
            deletePic(event) {
                this[`${event.name}ImgList`].splice(event.index, 1);
                this.form2.unit_sign = '';
            },
            // 新增图片
            async afterRead(event) {
                // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
                let lists = [].concat(event.file)
                let fileListLen = this[`${event.name}ImgList`].length
                lists.map((item) => {
                    this[`${event.name}ImgList`].push({
                        ...item,
                        status: 'uploading',
                        message: '上传中'
                    })
                })
                for (let i = 0; i < lists.length; i++) {
                    const result = await this.uploadFilePromise(lists[i].url)
                    let item = this[`${event.name}ImgList`][fileListLen]
                    this[`${event.name}ImgList`].splice(fileListLen, 1, Object.assign(item, {
                        status: 'success',
                        message: '',
                        url: result
                    }))
                    fileListLen++
                }
                this.form2.unit_sign = this.unitImgList[0].url;
            },
            uploadFilePromise(url) {
                let server = this.$url + '/api.php/index/file_update';
                return new Promise((resolve, reject) => {
                    uni.uploadFile({
                        url: server,
                        filePath: url,
                        name: 'image[]',
                        success: (res) => {
                            let resp = JSON.parse(res.data);
                            setTimeout(() => {
                                resolve(resp.data.img_url[0]);
                            }, 1000)
                        }
                    });
                })
            },

            save(){
                if ( this[`checked${this.type}`] === true){
                    this.$refs[`uForm${this.type}`].validate().then(res => {
                        let data = uni.$u.deepClone(this[`form${this.type}`]);
                        data.type = this.type;
                        data.u_id = uni.getStorageSync('u_id');
                        uni.$u.http.post('/api.php/landlord/sign_up', data).then(res => {
                            uni.showToast({
                                title: '保存成功', //提示文字
                                duration: 3000, //显示时长
                                icon: "success", //图标，支持"success"、"loading"
                            });
                            uni.navigateBack({delta:1});
                        })
                    }).catch(errors => {
                        uni.$u.toast('校验失败')
                    });
                }else{
                    uni.showToast({
                        title: '阅读并勾选免责', //提示文字
                        duration: 1500, //显示时长
                        icon: "error", //图标，支持"success"、"loading"
                    });
                }
            }
        }
    }
</script>

<style scoped>
    .page {
        width: 100%;
        min-height: 100vh;
        background-color: #ffffff;
    }
    .content{
        padding: 20rpx;
    }

    /deep/.u-form-item__body__left__content__label{
        padding-right: 20rpx;
    }
</style>